// ============================================================================
// 定时任务管理页面
// ============================================================================

import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { schedulerService, SchedulerStatus } from '../services/scheduler-service'
import { accountService } from '../services/account-service'
import { ScrapeTask, ScheduledTaskParams, WeiboLoginData, TaskProgress, TaskStatus } from '../../shared/types'
import { useNotifications } from '../hooks/use-notifications'
import { CreateTaskModal } from '../components/CreateTaskModal'
import { EditTaskModal } from '../components/EditTaskModal'
import ProgressBar from '../components/ProgressBar'
import { logger } from '../utils/logger'
import { ROUTES } from '../router'
import { IPC_EVENTS } from '../../shared/constants'
import { ipcService } from '../services/ipc-service'

/**
 * 定时任务管理页面组件
 */
export const SchedulerPage: React.FC = () => {
  const navigate = useNavigate()
  const [tasks, setTasks] = useState<ScrapeTask[]>([])
  const [accounts, setAccounts] = useState<WeiboLoginData[]>([])
  const [schedulerStatus, setSchedulerStatus] = useState<SchedulerStatus | null>(null)
  const [loading, setLoading] = useState(true)
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [selectedTask, setSelectedTask] = useState<ScrapeTask | null>(null)
  const [showEditModal, setShowEditModal] = useState(false)
  const [taskProgresses, setTaskProgresses] = useState<Record<string, TaskProgress>>({})
  const { showSuccess, showError } = useNotifications()

  // 加载数据
  useEffect(() => {
    loadData()

    // 定时刷新状态和任务列表
    const statusInterval = setInterval(loadSchedulerStatus, 30000) // 30秒刷新一次
    const tasksInterval = setInterval(loadTasks, 10000) // 10秒刷新一次任务列表

    // 监听任务进度更新
    const handleProgressUpdate = (taskId: string, progress: TaskProgress) => {
      setTaskProgresses(prev => ({
        ...prev,
        [taskId]: progress
      }))
    }

    // 监听任务状态变化
    const handleStatusChange = (taskId: string, status: TaskStatus) => {
      setTasks(prev => prev.map(task =>
        task.id === taskId ? { ...task, status } : task
      ))

      // 如果任务完成或失败，清除进度信息
      if (status === 'completed' || status === 'failed') {
        setTaskProgresses(prev => {
          const newProgresses = { ...prev }
          delete newProgresses[taskId]
          return newProgresses
        })
      }
    }

    // 注册IPC事件监听器
    ipcService.on(IPC_EVENTS.TASK_PROGRESS_UPDATE, handleProgressUpdate)
    ipcService.on(IPC_EVENTS.TASK_STATUS_CHANGE, handleStatusChange)

    return () => {
      clearInterval(statusInterval)
      clearInterval(tasksInterval)
      // 清理事件监听器
      ipcService.off(IPC_EVENTS.TASK_PROGRESS_UPDATE, handleProgressUpdate)
      ipcService.off(IPC_EVENTS.TASK_STATUS_CHANGE, handleStatusChange)
    }
  }, [])

  /**
   * 加载所有数据
   */
  const loadData = async () => {
    try {
      setLoading(true)
      await Promise.all([
        loadTasks(),
        loadAccounts(),
        loadSchedulerStatus()
      ])
    } catch (error) {
      logger.error('加载数据失败', error)
      showError('加载数据失败', `${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  /**
   * 加载定时任务列表
   */
  const loadTasks = async () => {
    try {
      const taskList = await schedulerService.getAllScheduledTasks()
      setTasks(taskList)
    } catch (error) {
      logger.error('加载定时任务失败', error)
      throw error
    }
  }

  /**
   * 加载账号列表
   */
  const loadAccounts = async () => {
    try {
      const accountList = await accountService.getAccounts()
      setAccounts(accountList.filter(acc => acc.isValid))
    } catch (error) {
      logger.error('加载账号列表失败', error)
      throw error
    }
  }

  /**
   * 加载调度器状态
   */
  const loadSchedulerStatus = async () => {
    try {
      const status = await schedulerService.getSchedulerStatus()
      setSchedulerStatus(status)
    } catch (error) {
      logger.error('加载调度器状态失败', error)
    }
  }

  /**
   * 启动/停止调度器
   */
  const toggleScheduler = async () => {
    try {
      if (schedulerStatus?.isRunning) {
        await schedulerService.stopScheduler()
        showSuccess('调度器已停止', '')
      } else {
        await schedulerService.startScheduler()
        showSuccess('调度器已启动', '')
      }
      await loadSchedulerStatus()
    } catch (error) {
      logger.error('切换调度器状态失败', error)
      showError('操作失败', '')
    }
  }

  /**
   * 立即执行任务
   */
  const executeTaskNow = async (taskId: string) => {
    try {
      await schedulerService.executeTaskNow(taskId)
      showSuccess('任务已开始执行', '')
      await loadTasks()
    } catch (error) {
      logger.error('执行任务失败', error)
      showError('执行任务失败', '')
    }
  }

  /**
   * 删除任务
   */
  const deleteTask = async (taskId: string) => {
    if (!confirm('确定要删除这个定时任务吗？')) {
      return
    }

    try {
      await schedulerService.deleteScheduledTask(taskId)
      showSuccess('任务已删除', '')
      await loadTasks()
    } catch (error) {
      logger.error('删除任务失败', error)
      showError('删除任务失败', '')
    }
  }

  /**
   * 切换任务启用状态
   */
  const toggleTaskEnabled = async (task: ScrapeTask) => {
    try {
      const params = task.params as ScheduledTaskParams
      const willDisable = params.enabled // 当前是启用状态，即将禁用

      // 如果要禁用任务且任务正在运行，先停止任务
      if (willDisable && task.status === 'running') {
        await ipcService.invoke(IPC_EVENTS.TASK_STOP, task.id)
        showSuccess('正在运行的任务已停止', '')
      }

      await schedulerService.updateScheduledTask(task.id, {
        enabled: !params.enabled
      })
      showSuccess(
        willDisable ? '任务已禁用' : '任务已启用',
        ''
      )
      await loadTasks()
    } catch (error) {
      logger.error('切换任务状态失败', error)
      showError('操作失败', '')
    }
  }

  /**
   * 编辑任务
   */
  const editTask = (task: ScrapeTask) => {
    setSelectedTask(task)
    setShowEditModal(true)
  }

  /**
   * 格式化下次执行时间
   */
  const formatNextExecution = (nextExecution?: Date | string | number) => {
    if (!nextExecution) return '未设置'

    // 确保转换为 Date 对象
    let date: Date
    if (nextExecution instanceof Date) {
      date = nextExecution
    } else if (typeof nextExecution === 'string') {
      date = new Date(nextExecution)
    } else if (typeof nextExecution === 'number') {
      date = new Date(nextExecution)
    } else {
      return '未设置'
    }

    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return '未设置'
    }

    const now = new Date()
    const diff = date.getTime() - now.getTime()

    if (diff <= 0) return '即将执行'

    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(minutes / 60)
    const days = Math.floor(hours / 24)

    if (days > 0) {
      return `${days}天${hours % 24}小时后`
    } else if (hours > 0) {
      return `${hours}小时${minutes % 60}分钟后`
    } else {
      return `${minutes}分钟后`
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-lg text-gray-600">加载中...</div>
      </div>
    )
  }

  return (
    <div className="p-6 space-y-6">
      {/* 页面标题和调度器控制 */}
      <div className="flex items-center justify-between">
        <div></div>

        <div className="flex items-center space-x-4">
          {/* 调度器状态 */}
          <div className="flex items-center space-x-2">
            <div className={`w-3 h-3 rounded-full ${schedulerStatus?.isRunning ? 'bg-green-500' : 'bg-red-500'
              }`} />
            <span className="text-sm text-gray-600">
              调度器{schedulerStatus?.isRunning ? '运行中' : '已停止'}
            </span>
          </div>

          {/* 调度器控制按钮 */}
          <button
            onClick={toggleScheduler}
            className={`px-4 py-2 rounded-lg text-sm font-medium ${schedulerStatus?.isRunning
              ? 'bg-red-100 text-red-700 hover:bg-red-200'
              : 'bg-green-100 text-green-700 hover:bg-green-200'
              }`}
          >
            {schedulerStatus?.isRunning ? '停止调度器' : '启动调度器'}
          </button>

          {/* 查看日志按钮 */}
          <button
            onClick={() => navigate(ROUTES.LOGS)}
            className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 text-sm font-medium"
          >
            查看日志
          </button>

          {/* 创建任务按钮 */}
          <button
            onClick={() => setShowCreateModal(true)}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm font-medium"
          >
            创建定时任务
          </button>
        </div>
      </div>

      {/* 调度器统计信息 */}
      {schedulerStatus && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="bg-white p-4 rounded-lg border">
            <div className="text-2xl font-bold text-blue-600">
              {schedulerStatus.totalJobs}
            </div>
            <div className="text-sm text-gray-600">总任务数</div>
          </div>

          <div className="bg-white p-4 rounded-lg border">
            <div className="text-2xl font-bold text-green-600">
              {schedulerStatus.activeJobs}
            </div>
            <div className="text-sm text-gray-600">活跃任务</div>
          </div>

          <div className="bg-white p-4 rounded-lg border">
            <div className="text-sm font-medium text-gray-900">
              {formatNextExecution(schedulerStatus.nextExecution)}
            </div>
            <div className="text-sm text-gray-600">下次执行</div>
          </div>

          <div className="bg-white p-4 rounded-lg border">
            <div className="text-2xl font-bold text-red-600">
              {schedulerStatus.errors.length}
            </div>
            <div className="text-sm text-gray-600">错误数</div>
          </div>
        </div>
      )}

      {/* 任务列表 */}
      <div className="bg-white rounded-lg border">
        <div className="px-6 py-4 border-b">
          <h2 className="text-lg font-semibold text-gray-900">定时任务列表</h2>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  任务信息
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  关键字
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  执行间隔
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  状态
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  进度
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  下次执行
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {tasks.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-6 py-8 text-center text-gray-500">
                    暂无定时任务
                  </td>
                </tr>
              ) : (
                tasks.map((task) => {
                  const params = task.params as ScheduledTaskParams
                  const account = accounts.find(acc => `${acc.id}` === task.accountId)

                  return (
                    <tr key={task.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4">
                        <div>
                          <div className="text-sm font-medium text-gray-900">
                            {task.id.slice(0, 8)}...
                          </div>
                          <div className="text-sm text-gray-500">
                            账号: {account?.userInfo.screen_name || '未知'}
                          </div>
                          <div className="text-xs text-gray-400">
                            创建: {new Date(task.createdAt).toLocaleString()}
                          </div>
                        </div>
                      </td>

                      <td className="px-6 py-4">
                        <div className="flex flex-wrap gap-1">
                          {params.keywords.slice(0, 3).map((keyword, index) => (
                            <span
                              key={index}
                              className="inline-block px-2 py-1 text-xs bg-blue-100 text-blue-800 rounded"
                            >
                              {keyword}
                            </span>
                          ))}
                          {params.keywords.length > 3 && (
                            <span className="text-xs text-gray-500">
                              +{params.keywords.length - 3}个
                            </span>
                          )}
                        </div>
                      </td>

                      <td className="px-6 py-4 text-sm text-gray-900">
                        {schedulerService.formatInterval(params.interval)}
                      </td>

                      <td className="px-6 py-4">
                        <div className="flex items-center space-x-2">
                          <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${params.enabled
                            ? 'bg-green-100 text-green-800'
                            : 'bg-gray-100 text-gray-800'
                            }`}>
                            {params.enabled ? '启用' : '禁用'}
                          </span>
                          <span className={`text-xs ${schedulerService.getTaskStatusColor(task.status)}`}>
                            {schedulerService.getTaskStatusText(task.status)}
                          </span>
                        </div>
                      </td>

                      {/* 进度列 */}
                      <td className="px-6 py-4">
                        {taskProgresses[task.id] ? (
                          <div className="min-w-48">
                            <ProgressBar
                              progress={taskProgresses[task.id]!}
                              status={task.status as 'pending' | 'running' | 'completed' | 'failed'}
                              showDetails={true}
                              className="text-xs"
                            />
                          </div>
                        ) : task.status === 'running' ? (
                          <div className="flex items-center space-x-2">
                            <div className="w-2 h-2 bg-blue-500 rounded-full animate-pulse"></div>
                            <span className="text-xs text-gray-500">爬取中...</span>
                          </div>
                        ) : task.status === 'completed' ? (
                          <div className="flex items-center space-x-2">
                            <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                            <span className="text-xs text-green-600">已完成</span>
                          </div>
                        ) : task.status === 'failed' ? (
                          <div className="flex items-center space-x-2">
                            <div className="w-2 h-2 bg-red-500 rounded-full"></div>
                            <span className="text-xs text-red-600">已失败</span>
                          </div>
                        ) : (
                          <span className="text-xs text-gray-400">-</span>
                        )}
                      </td>

                      <td className="px-6 py-4 text-sm text-gray-900">
                        {formatNextExecution(params.nextExecution)}
                      </td>

                      <td className="px-6 py-4">
                        <div className="flex items-center space-x-2">
                          <button
                            onClick={() => executeTaskNow(task.id)}
                            disabled={!params.enabled}
                            className="text-blue-600 hover:text-blue-900 text-sm disabled:text-gray-400"
                          >
                            立即执行
                          </button>

                          <button
                            onClick={() => editTask(task)}
                            className="text-green-600 hover:text-green-900 text-sm"
                          >
                            编辑
                          </button>

                          <button
                            onClick={() => toggleTaskEnabled(task)}
                            className="text-yellow-600 hover:text-yellow-900 text-sm"
                          >
                            {params.enabled ? '禁用' : '启用'}
                          </button>

                          <button
                            onClick={() => deleteTask(task.id)}
                            className="text-red-600 hover:text-red-900 text-sm"
                          >
                            删除
                          </button>
                        </div>
                      </td>
                    </tr>
                  )
                })
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* 创建任务模态框 */}
      {showCreateModal && (
        <CreateTaskModal
          accounts={accounts}
          onClose={() => setShowCreateModal(false)}
          onSuccess={() => {
            setShowCreateModal(false)
            loadTasks()
          }}
        />
      )}

      {/* 编辑任务模态框 */}
      {showEditModal && selectedTask && (
        <EditTaskModal
          task={selectedTask}
          accounts={accounts}
          onClose={() => {
            setShowEditModal(false)
            setSelectedTask(null)
          }}
          onSuccess={() => {
            setShowEditModal(false)
            setSelectedTask(null)
            loadTasks()
          }}
        />
      )}
    </div>
  )
}
